package com.yonyou.hxjy.job;

import cn.hutool.json.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.hxjy.dao.JobLogDao;
import com.yonyou.hxjy.service.dingtalk.DingtalkAccessTokenGetService;
import com.yonyou.hxjy.service.dingtalk.DingtalkProcessInstanceGet;
import com.yonyou.hxjy.service.bm.BmYonsuiteService;
import com.yonyou.hxjy.service.dingtalk.DingtalkProcessInstanceToYs;
import com.yonyou.hxjy.service.dingtalk.Impl.toysImpl.DingtalkProcessInstanceToYsImplTest;
import com.yonyou.hxjy.service.dingtalk.Impl.YsDataGetService;
import com.yonyou.hxjy.service.dingtalk.enums.ProcessInstanceConstant;
import com.yonyou.hxjy.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Component
@RestController
public class DingdingJob {

    private static final Logger logger = LoggerFactory.getLogger(DingdingJob.class);

    @Autowired
    public BmYonsuiteService bmYonsuiteService;

    @Resource
    public JobLogDao jobLogDao;

    @Autowired
    private YsDataGetService ysDataGetService;

    @Autowired
    private DingtalkAccessTokenGetService dingtalkAccessTokenGetService;

    @Autowired
    private DingtalkProcessInstanceGet dingtalkProcessInstanceGet;

    @Autowired
    private DingtalkProcessInstanceToYs dingtalkProcessInstanceToYs;

    @Autowired
    private DingtalkProcessInstanceToYsImplTest dingtalkProcessInstanceToYsImplTest;

    //费用报销同步
    @XxlJob("queryDDApproveReimbursement")
    @GetMapping("/getDingDingJob")
    public List<String> DingDingExpenseClaimToYsJob() throws Exception {
        //判断定时任务是否传参数
        String param = XxlJobHelper.getJobParam();
        JSONObject timeQueryParam = getQueryParam(param);
        String startTime = timeQueryParam.get("Start").toString();
        String endTime = timeQueryParam.get("End").toString();
        Map<String, Object> params = new HashMap<>();
        List<String> statuses = new ArrayList<>();
//        statuses.add("COMPLETED"); //获取完成审批的实例id
        //获取费用报销审批实例Id列表
        params.put("processCode", ProcessInstanceConstant.EXPENSE_CLAIM_CODE_NEW);
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        //params.put("startTime","1746673781000"); //5月08日
        //params.put("endTime","1747019381000"); //5月12日
        params.put("nextToken",0);
        params.put("maxResults",20);
        params.put("statuses",statuses);
        //获取审批实例ID
        List<String> processInstanceId = dingtalkProcessInstanceGet.getProcessInstanceId(params,"费用报销");
        logger.info("processInstanceId: {}", processInstanceId);
        logger.info("列表size: {}", processInstanceId.size());

//        //获取审批实例详情
//        long startGetTime = System.currentTimeMillis();
//        List<JSONObject> processInstanceDetails = dingtalkProcessInstanceGet.getProcessInstanceDetails("费用报销");
//        long endGetTime = System.currentTimeMillis();
//        if (processInstanceDetails == null) {
//            return new ReturnT<>(ReturnT.FAIL_CODE,"审批实例为空!");
//        }
//        System.out.println("获取全部审批实例大小"+processInstanceDetails.size()+"共耗时:" + (endGetTime - startGetTime));
//
//        //将费用报销付款单数据保存到ys中
//        List<JSONObject> jsonObjects = dingtalkProcessInstanceToYs.expenseClaim_toYsJson(processInstanceDetails);
//        ReturnT<List> returnT = new ReturnT<>();
//        if (!processInstanceDetails.isEmpty()) {
//            returnT.setContent(jsonObjects);
//            returnT.setCode(200);
//        }
        return processInstanceId;
    }
    //费用报销明细同步
    @XxlJob("queryDDApproveReimbursementDetails")
//    @GetMapping("/getDingDingJob")
    public ReturnT<List> DingDingExpenseClaimDetailsToYsJob() throws Exception {
        //获取审批实例详情
        long startGetTime = System.currentTimeMillis();
        Map<String,Object> map = dingtalkProcessInstanceGet.getProcessInstanceDetails("费用报销");
        List<JSONObject> processInstanceDetails = List.class.cast(map.get("jsonObjectList"));
        List<String> processInstanceIdList = List.class.cast(map.get("processInstanceIdList"));
        long endGetTime = System.currentTimeMillis();
        if (processInstanceDetails == null) {
            return new ReturnT<>(ReturnT.FAIL_CODE,"审批实例为空!");
        }
        System.out.println("获取全部审批实例大小"+processInstanceDetails.size()+"共耗时:" + (endGetTime - startGetTime));

        //将费用报销付款单数据保存到ys中
        List<JSONObject> jsonObjects = dingtalkProcessInstanceToYs.newExpenseClaim_toYsJson(processInstanceDetails);
        ReturnT<List> returnT = new ReturnT<>();
        if (!processInstanceDetails.isEmpty()) {
//            returnT.setContent(jsonObjects);
            returnT.setCode(200);
        }
        return returnT;
    }
    //预付款同步主表
    @XxlJob("queryDDApprovePayment")
    @GetMapping("/getDingDingAdvancePaymentJob")
    public List<String> DingDingAdvancePaymentToYsJob() throws Exception {
        //判断定时任务是否传参数
        String param = XxlJobHelper.getJobParam();
        JSONObject timeQueryParam = getQueryParam(param);
        String startTime = timeQueryParam.get("Start").toString();
        String endTime = timeQueryParam.get("End").toString();
        Map<String, Object> params = new HashMap<>();
        List<String> statuses = new ArrayList<>();
//        statuses.add("RUNNING"); //获取审批中的实例id
        //获取费用报销审批实例Id列表
        params.put("processCode", ProcessInstanceConstant.ADVANCE_PAYMENT_CODE_NEW);
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        //params.put("startTime","1748499805000"); //23日8点
        //params.put("endTime","1748507005000"); //27日12点
        params.put("nextToken",0);
        params.put("maxResults",20);
        params.put("statuses",statuses);
        //获取审批实例ID
        List<String> processInstanceId = dingtalkProcessInstanceGet.getProcessInstanceId(params,"预付款,借款,备用金");
        logger.info("processInstanceId: {}", processInstanceId);
        logger.info("列表size: {}", processInstanceId.size());
        return processInstanceId;
    }

    //预付款单明细同步
    @XxlJob("queryDDApprovePaymentDetails")
//    @GetMapping("/getDingDingAdvancePaymentJob")
    public ReturnT<List> DingDingAdvancePaymentDetailsToYsJob() throws Exception {
        //判断定时任务是否传参数
        String param = XxlJobHelper.getJobParam();
        //获取审批实例详情
        long startGetTime = System.currentTimeMillis();
        Map<String,Object> map  = dingtalkProcessInstanceGet.getProcessInstanceDetails("预付款,借款,备用金");
        List<JSONObject> processInstanceDetails = List.class.cast(map.get("jsonObjectList"));
        long endGetTime = System.currentTimeMillis();
        if (processInstanceDetails == null || processInstanceDetails.isEmpty()) {
            return new ReturnT<>(ReturnT.FAIL_CODE,"审批实例为空!");
        }
        System.out.println("获取全部审批实例大小"+processInstanceDetails.size()+"共耗时:" + (endGetTime - startGetTime));
        //将预付款付款单数据保存到ys中
        List<JSONObject> jsonObjects = dingtalkProcessInstanceToYs.newadvancePayment_toYsJson(processInstanceDetails);
        ReturnT<List> returnT = new ReturnT<>();
        if (!processInstanceDetails.isEmpty()) {
//            returnT.setContent(jsonObjects);
            returnT.setCode(200);
        }
        return returnT;
    }
    //资金调拨单据同步
    @XxlJob("queryDingDingFundAllocationJob")
    @GetMapping("/queryDingDingFundAllocationJob")
    public List<String> queryDingDingFundAllocationJob() throws Exception {
        //判断定时任务是否传参数
        String param = XxlJobHelper.getJobParam();
        JSONObject timeQueryParam = getQueryParam(param);
        String startTime = timeQueryParam.get("Start").toString();
        String endTime = timeQueryParam.get("End").toString();
        Map<String, Object> params = new HashMap<>();
        List<String> statuses = new ArrayList<>();
//        statuses.add("RUNNING"); //获取审批中的实例id
        //获取费用报销审批实例Id列表
        params.put("processCode", ProcessInstanceConstant.FUND_ALLOCATION_CODE);
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        //params.put("startTime","1748499805000"); //23日8点
        //params.put("endTime","1748507005000"); //27日12点
        params.put("nextToken",0);
        params.put("maxResults",20);
//        params.put("statuses",statuses);
        //获取审批实例ID
        List<String> processInstanceId = dingtalkProcessInstanceGet.getProcessInstanceId(params,"资金调拨");
        logger.info("processInstanceId: {}", processInstanceId);
        logger.info("列表size: {}", processInstanceId.size());
        return processInstanceId;
    }



    //资金调拨明细单据同步
    @XxlJob("queryDingDingFundAllocationJobDetail")
    @GetMapping("/queryDingDingFundAllocationJobDetail")
    public ReturnT<List> queryDingDingFundAllocationJobDetail() throws Exception {
        //判断定时任务是否传参数
        String param = XxlJobHelper.getJobParam();
        //获取审批实例详情
        long startGetTime = System.currentTimeMillis();
        Map<String,Object> map  = dingtalkProcessInstanceGet.getProcessInstanceDetails("资金调拨");
        List<JSONObject> processInstanceDetails = List.class.cast(map.get("jsonObjectList"));
        long endGetTime = System.currentTimeMillis();
        if (processInstanceDetails == null || processInstanceDetails.isEmpty()) {
            return new ReturnT<>(ReturnT.FAIL_CODE,"审批实例为空!");
        }
        System.out.println("获取全部审批实例大小"+processInstanceDetails.size()+"共耗时:" + (endGetTime - startGetTime));
        //将预付款付款单数据保存到ys中
        List<JSONObject> jsonObjects = dingtalkProcessInstanceToYs.fundAllocation_toYsJson(processInstanceDetails);
        ReturnT<List> returnT = new ReturnT<>();
        if (!processInstanceDetails.isEmpty()) {
//            returnT.setContent(jsonObjects);
            returnT.setCode(200);
        }
        return returnT;
    }

    @XxlJob("panzhi3")
    @GetMapping("/getDingDingFundAllocationJob")
    public ReturnT<List> DingDingFundAllocationToYsJsonJob() throws Exception {
        //判断定时任务是否传参数
        String param = XxlJobHelper.getJobParam();
        JSONObject timeQueryParam = getQueryParam(param);
        String startTime = timeQueryParam.get("Start").toString();
        String endTime = timeQueryParam.get("End").toString();
        Map<String, Object> params = new HashMap<>();
        List<String> statuses = new ArrayList<>();
//        statuses.add("RUNNING"); //获取完成审批的实例id
        //获取费用报销审批实例Id列表
        params.put("processCode", ProcessInstanceConstant.FUND_ALLOCATION_CODE_NEW);
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        //params.put("startTime","1747965206000"); //2024年10月01日
        //params.put("endTime","1747979606000"); //2024年01月01日
        params.put("nextToken",0);
        params.put("maxResults",20);
        params.put("statuses",statuses);
        //获取审批实例ID
        List<String> processInstanceId = dingtalkProcessInstanceGet.getProcessInstanceId(params,"资金调拨");
        logger.info("processInstanceId: {}", processInstanceId);
        logger.info("列表size: {}", processInstanceId.size());

        //获取审批实例详情
        Map<String,Object> map = dingtalkProcessInstanceGet.getProcessInstanceDetails("资金调拨");
        List<JSONObject> processInstanceDetails = List.class.cast(map.get("jsonObjectList"));
        if (processInstanceDetails == null || processInstanceDetails.isEmpty()) {
            return new ReturnT<>(ReturnT.FAIL_CODE,"审批实例为空!");
        }
        //将资金调拨付款单数据保存到ys中
        List<JSONObject> jsonObjects = dingtalkProcessInstanceToYs.fundAllocation_toYsJson(processInstanceDetails);
        ReturnT<List> returnT = new ReturnT<>();
        if (!processInstanceDetails.isEmpty()) {
            returnT.setContent(jsonObjects);
            returnT.setCode(200);
        }
        return returnT;
    }


    @GetMapping("/getOrgCode")
    public ReturnT<String> getOrgCode(@RequestParam String code){
        String uitCode = ysDataGetService.getOrgUitCode(code);
        return new ReturnT<>(uitCode);
        //return ReturnT.SUCCESS;
    }

    @GetMapping("/getBankDetail")
    public ReturnT<List> getBankDetail(){
        //List<JSONObject> jsonObjectList = ysDataGetService.getBankDetailsMessage();
        List<JSONObject> jsonObjectList = ysDataGetService.getVendorDetailsMessage();
        //String vendorCode = dingtalkProcessInstanceToYsImplTest.getVendorCode("yw", "122", jsonObjectList);
        //logger.info(vendorCode);
        return new ReturnT<>(jsonObjectList);
        //return ReturnT.SUCCESS;
    }


    public static JSONObject getQueryParam(String param) {
        JSONObject timeQueryParam = new JSONObject();

        if (param != null && !param.isEmpty()) {
            List<String> timeRange = Arrays.asList(param.split("\\|"));
            System.out.println(timeRange);
            // 定义日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long startTimestamp = 0;
            long endTimestamp = 0;
            try {
                // 将字符串解析为 Date 对象
                Date dateStart = sdf.parse(timeRange.get(0));
                Date dateEnd = sdf.parse(timeRange.get(1));
                startTimestamp = dateStart.getTime();
                endTimestamp = dateEnd.getTime();

            } catch (ParseException e) {
                e.printStackTrace();
            }
            timeQueryParam.set("Start", startTimestamp);
            timeQueryParam.set("End", endTimestamp);

        } else {
            String startDateBy10m = DateUtils.getStartDateBy10m();
            String endDateBy10m = DateUtils.getEndDateBy10m();
            // 定义日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long startTimestamp = 0;
            long endTimestamp = 0;
            try {
                // 将字符串解析为 Date 对象
                Date dateStart = sdf.parse(startDateBy10m);
                Date dateEnd = sdf.parse(endDateBy10m);
                startTimestamp = dateStart.getTime();
                endTimestamp = dateEnd.getTime();

            } catch (ParseException e) {
                e.printStackTrace();
            }
            timeQueryParam.set("Start", startTimestamp);
            timeQueryParam.set("End", endTimestamp);
        }
        return timeQueryParam;
    }

    public static String dealTime(String oldTime){

        OffsetDateTime offsetDateTime = OffsetDateTime.parse(oldTime);
        // 定义目标格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化为指定格式
        String formattedTime = offsetDateTime.format(formatter);

        return formattedTime;
    }
}
